package com.gues.shiro;

import ch.qos.logback.core.encoder.ByteArrayUtil;
import com.gues.eneity.User;
import com.gues.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

public class UserRealm extends AuthorizingRealm {

    @Resource
    UserService userService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    // 认证
    @Override
    protected SimpleAuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        // 用户名
        String principal = (String) authenticationToken.getPrincipal();
        // 密码 + 盐 + 散列
        // 对输入的密码加密
        User user = userService.selectUserByUsernamer(principal);
        if ( !ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), this.getName());
        }
        return null;  // 空指针异常
    }
}
